/**
 * Description：检验待处理 hooks
 * Copyright (c) : 通力凯顿（北京）系统集成有限公司
 * Writer：朱楠
 * date: 2024.8.19
 */
const { ref, reactive } = Vue
import { useFetch } from '../../../Scripts/hooks/useFetch.js'
const { ElMessage, ElMessageBox } = ElementPlus

export function useCheckSuspending() {
  const baseAPI = '../../../Ashx/ContainerCheckSuspendingVue3PageHandler.ashx';
  let currentUserInfo = {};// 当前登录用户信息

  const checkSuspendingFormRef = ref(null);//表单ref

  const checkSuspendingObj = reactive({
    dialogVisible: false,
    tabname: 'first',
    // 表单
    form: {
      notes: '',//备注
    },
    dataList: [],
    // 表单校验
    formRules: {
      notes: [{ required: true, message: '【备注】不能为空', trigger: 'blur' }]
    }
  });

  // 初始化数据
  async function initCheckSuspendingDialogData(selectionRows, userInfo) {
    checkSuspendingObj.dialogVisible = true;
    currentUserInfo = userInfo.value;
    checkSuspendingObj.dataList = selectionRows;
    await getContainerCheckSuspending(selectionRows);//查询检验备注
  }

  // 查询检验备注
  async function getContainerCheckSuspending(selectionRows) {
    const { data } = await useFetch({
      url: `${baseAPI}?actions=getContainerCheckSuspending`,
      data: { type: 'getContainerCheckSuspending', postData: selectionRows }
    });
    checkSuspendingObj.form.notes = data.value;
  }

  // 【提交】按钮点击
  async function handleCheckSuspendingSubmitClick() {
    if (!await validate()) { return; }


    ElMessageBox.confirm(`你确认要提交吗?`, '确认', { type: 'warning' }).then(async () => {
      const { data, status: { msg } } = await useFetch({
        url: `${baseAPI}?actions=saveData`,
        data: {
          type: 'saveData',
          postData: checkSuspendingObj.dataList,
          notes: checkSuspendingObj.form.notes,
          employeeid: currentUserInfo.employeeid,
          factoryid: currentUserInfo.factoryid
        }
      });
      if (data.value === true) {
        ElMessage({ type: 'success', message: `保存成功`, grouping: true });
        checkSuspendingFormRef.value.resetFields();//重置表单数据
        checkSuspendingObj.dialogVisible = false;
      } else {
        ElMessage({ type: 'error', message: msg, grouping: true });
      }
    }).catch(() => {
      ElMessage({ type: 'info', message: '已取消' });
    });
  }

  async function validate() {
    try {
      await checkSuspendingFormRef.value.validate();
    } catch (error) {
      return false;
    }
    return true;
  }

  return {
    checkSuspendingObj,
    checkSuspendingFormRef,
    initCheckSuspendingDialogData,
    handleCheckSuspendingSubmitClick,
  };
}